package com.canbot.u05.utils;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.Log;

import java.io.File;

public class MediaScanner {

        private static final String TAG = "MediaScanner";

        private MediaScannerConnection mConn = null;

        private SannerClient mClient = null;

        private File mFile = null;

        private String mMimeType = null; //�ļ�����

        public MediaScanner(Context context) {
                if (mClient == null) {
                        mClient = new SannerClient();
                }
                if (mConn == null) {
                        mConn = new MediaScannerConnection(context, mClient);
                }
        }

        class SannerClient implements
                MediaScannerConnection.MediaScannerConnectionClient {

                public void onMediaScannerConnected() {

                        if (mFile == null) {
                                return;
                        }
                        scan(mFile, mMimeType);
                }

                public void onScanCompleted(String path, Uri uri) {
                        Log.i(TAG, "ɨ�����");
                        mConn.disconnect();

                }
        }

        /**
         * ʹ��MediaScannerConnection���ļ�ɨ�赽ý���
         *
         * @param file
         * @param type
         */
        private void scan(File file, String type) {
                Log.i(TAG, "scan " + file.getAbsolutePath());
                if (file.isFile()) {
                        mConn.scanFile(file.getAbsolutePath(), type);
                        ;
                        return;
                }
                File[] files = file.listFiles();
                if (files == null) {
                        return;
                }
                for (File f : file.listFiles()) {
                        scan(f, type);
                }
        }

        /**
         * ɨ���ļ����ļ��е�ý���
         *
         * @param file
         * @param mimeType �ļ�����
         */
        public void scanFile(File file, String mimeType) {
                mFile = file;
                mMimeType = mimeType;
                mConn.connect();
        }
}
